import logging
import requests
from wxauto import WeChat

# 配置日志记录基本设置，将日志信息输出到控制台，设置日志级别为INFO
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 打开微信窗口
wx = WeChat()

while True:
    msgs = wx.GetAllNewMessage()
    if len(msgs) != 0:
        for sender, message_list in msgs.items():
            # 判断发送者是否为王鹏辉，如果是则跳过回复
            if sender == '肚笨猪':
                logging.info(f"收到来自 {sender} 的消息，将自动跳过")
                continue
            for msg in message_list:
                logging.info(f"收到来自 {sender} 的消息: {msg}")
                url = f'http://api.qingyunke.com/api.php?key=free&appid=0&msg={msg}'
                try:
                    response = requests.get(url)
                    response.raise_for_status()  # 检查请求是否成功，若不成功则抛出异常
                    try:
                        content = response.json()['content'].replace('{br}', '')
                        wx.SendMsg(content, sender)
                        logging.info(f"已向 {sender} 回复消息: {content}")
                        # 回复一条消息后，切换到微信运动聊天窗口，这里可根据实际需求优化切换逻辑
                        who = '文件传输助手'
                        wx.ChatWith(who=who)
                        break
                    except KeyError:
                        logging.error(f"获取回复内容出现 KeyError 异常，消息内容: {msg}")
                        continue
                    except requests.RequestException as e:
                        logging.error(f"请求接口出现异常: {e}")
                        continue
                except requests.RequestException as e:
                    logging.error(f"请求接口出现异常: {e}")
                    continue
            break
    else:
        who = '文件传输助手'
        wx.ChatWith(who=who)